"use strict";
module.exports = {
    /**ServiceCore、服务器核心程序，仅能允许模块内部函数调用，不可随意操作*/
    async ServiceCore(Instance, ConfigureData) {
        let {
            DefaultPage,
            DefaultRootPath,
            EnableHistoryRouter,
            ExternalImportRouter,
            ServicePort,
            ServiceHost,
            SpecialSupport,
            SSLPrivateKey,
            SSLCertificate,
            NoRequiredStaticResources
        } = ConfigureData;
        let globalRouter;
        let httpDoubleRouter;
        let httpPort;
        let httpPath;
        let httpDefaultPage;
        let httpHistoryRouter;
        let httpHostOrAddress;
        let httpNoNeedStatic;
        let httpsDoubleRouter;
        let httpsPort;
        let httpsPath;
        let httpsDefaultPage;
        let httpsHistoryRouter;
        let httpsHostOrAddress;
        let httpsNoNeedStatic;
        let http_Success;
        let https_Success;
        switch (Instance.__ToolKit.DataTypeDetect(DefaultRootPath)) {
            case "obj":
                httpPath = DefaultRootPath.http;
                httpsPath = DefaultRootPath.https;
                break;
            case "str":
                httpPath = DefaultRootPath;
                httpsPath = DefaultRootPath;
                break;
        }
        switch (Instance.__ToolKit.DataTypeDetect(DefaultPage)) {
            case "obj":
                httpDefaultPage = DefaultPage.http;
                httpsDefaultPage = DefaultPage.https;
                break;
            case "str":
                httpDefaultPage = DefaultPage;
                httpsDefaultPage = DefaultPage;
                break;
        }
        switch (Instance.__ToolKit.DataTypeDetect(ServicePort)) {
            case "obj":
                httpPort = ServicePort.http;
                httpsPort = ServicePort.https;
                break;
            case "num":
                if (Instance.__MeTools.ModeLauncherSelect(ConfigureData) !== "both") {
                    httpPort = ServicePort;
                    httpsPort = ServicePort;
                }
                break;
        }
        switch (Instance.__ToolKit.DataTypeDetect(ServiceHost)) {
            case "obj":
                httpHostOrAddress = ServiceHost.http;
                httpsHostOrAddress = ServiceHost.https;
                break;
            case "str":
                httpHostOrAddress = ServiceHost;
                httpsHostOrAddress = ServiceHost;
                break;
            default:
                httpHostOrAddress = undefined;
                httpsHostOrAddress = undefined;
                break;
        }
        switch (Instance.__ToolKit.DataTypeDetect(EnableHistoryRouter)) {
            case "obj":
                httpHistoryRouter = EnableHistoryRouter.http;
                httpsHistoryRouter = EnableHistoryRouter.https;
                break;
            case "boo":
                httpHistoryRouter = EnableHistoryRouter;
                httpsHistoryRouter = EnableHistoryRouter;
                break;
        }
        switch (Instance.__ToolKit.DataTypeDetect(ExternalImportRouter)) {
            case "obj":
                httpDoubleRouter = ExternalImportRouter.http;
                httpsDoubleRouter = ExternalImportRouter.https;
                globalRouter = ExternalImportRouter.global;
                break;
        }
        switch (Instance.__ToolKit.DataTypeDetect(NoRequiredStaticResources)) {
            case "obj":
                httpNoNeedStatic = NoRequiredStaticResources.http;
                httpsNoNeedStatic = NoRequiredStaticResources.https;
                break;
            case "boo":
                httpNoNeedStatic = NoRequiredStaticResources;
                httpsNoNeedStatic = NoRequiredStaticResources;
                break;
        }
        function MessageTips(ServerType, port, host) {
            switch (String(ServerType).toLowerCase()) {
                case "http":
                    if (Object.prototype.toString.call(host) === "[object String]") {
                        if (parseInt(httpPort) === 80) {
                            Instance.__InstanceCollect_Root.consoleLogStream.addonLog(Instance, `网站服务器模块、http服务启动成功。网站协议：http，端口号：${port}，网络地址：http://${host}`, "ok");
                        } else {
                            Instance.__InstanceCollect_Root.consoleLogStream.addonLog(Instance, `网站服务器模块、http服务启动成功。网站协议：http，端口号：${port}，网络地址：http://${host}:${port}`, "ok");
                        }
                    } else {
                        Instance.__InstanceCollect_Root.consoleLogStream.addonLog(Instance, `网站服务器模块、http服务启动成功。网站协议：http，端口号：${port}`, "ok");
                    }
                    break;
                case "https":
                    if (Object.prototype.toString.call(host) === "[object String]") {
                        if (parseInt(port) === 443) {
                            Instance.__InstanceCollect_Root.consoleLogStream.addonLog(Instance, `网站服务器模块、https服务启动成功。网站协议：https，端口号：${port}，网络地址：https://${host}`, "ok");
                        } else {
                            Instance.__InstanceCollect_Root.consoleLogStream.addonLog(Instance, `网站服务器模块、https服务启动成功。网站协议：https，端口号：${port}，网络地址：https://${host}:${port}`, "ok");
                        }
                    } else {
                        Instance.__InstanceCollect_Root.consoleLogStream.addonLog(Instance, `网站服务器模块、https服务启动成功。网站协议：https，端口号：${port}`, "ok");
                    }
                    break;
            }
        }
        function SSL_authLoader(PrivateKeyPath, CertificatePath) {
            let FinalDataObj = {
                key: undefined,
                cert: undefined
            }
            FinalDataObj.key = Instance.__ToolKit.FileStream.readFileSync(PrivateKeyPath, "utf-8");
            FinalDataObj.cert = Instance.__ToolKit.FileStream.readFileSync(CertificatePath, "utf-8");
            return FinalDataObj;
        }
        function ModePreviewLoader(isBoth) {
            if (Boolean(isBoth).valueOf()) {
                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._RootDirPoint = [];
                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint = [];
                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteCore = [];

                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[0] = Instance.__InstanceCollect_Root.PluginPoint.webApp();
                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[1] = Instance.__InstanceCollect_Root.PluginPoint.webApp();
                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[0].use(Instance.__InstanceCollect_Root.PluginPoint.webApp.json(), Instance.__InstanceCollect_Root.PluginPoint.webApp.urlencoded({extended: true}));
                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[1].use(Instance.__InstanceCollect_Root.PluginPoint.webApp.json(), Instance.__InstanceCollect_Root.PluginPoint.webApp.urlencoded({extended: true}));
            } else {
                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint = Instance.__InstanceCollect_Root.PluginPoint.webApp();
                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint.use(Instance.__InstanceCollect_Root.PluginPoint.webApp.json(), Instance.__InstanceCollect_Root.PluginPoint.webApp.urlencoded({extended: true}));
            }
        }
        function SingleModeSpecialSupportPreviewLoader(ServiceMode, SpecialSupportSource) {
            switch (Object.prototype.toString.call(SpecialSupportSource)) {
                case "[object Object]":
                    switch (String(ServiceMode).toLowerCase()) {
                        case "http":
                            if (Instance.__ToolKit.emptyArrayDetect(SpecialSupportSource.http) === false) {
                                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint.use(...SpecialSupportSource.http);
                            }
                            if (Instance.__ToolKit.emptyArrayDetect(SpecialSupportSource.global) === false) {
                                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint.use(...SpecialSupportSource.global);
                            }
                            break;
                        case "https":
                            if (Instance.__ToolKit.emptyArrayDetect(SpecialSupportSource.https) === false) {
                                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint.use(...SpecialSupportSource.https);
                            }
                            if (Instance.__ToolKit.emptyArrayDetect(SpecialSupportSource.global) === false) {
                                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint.use(...SpecialSupportSource.global);
                            }
                            break;
                    }
                    break;
                case "[object Array]":
                    if (Instance.__ToolKit.emptyArrayDetect(SpecialSupportSource) === false) {
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint.use(...SpecialSupportSource);
                    }
                    break;
            }
        }
        function DoubleModeSpecialSupportPreviewLoader(SpecialSupportSource) {
            switch (Object.prototype.toString.call(SpecialSupportSource)) {
                case "[object Object]":
                    if (Instance.__ToolKit.emptyArrayDetect(SpecialSupportSource.http) === false) {
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[0].use(...SpecialSupportSource.http);
                    }
                    if (Instance.__ToolKit.emptyArrayDetect(SpecialSupportSource.global) === false) {
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[0].use(...SpecialSupportSource.global);
                    }
                    if (Instance.__ToolKit.emptyArrayDetect(SpecialSupportSource.https) === false) {
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[1].use(...SpecialSupportSource.https);
                    }
                    if (Instance.__ToolKit.emptyArrayDetect(SpecialSupportSource.global) === false) {
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[1].use(...SpecialSupportSource.global);
                    }
                    break;
                case "[object Array]":
                    if (Instance.__ToolKit.emptyArrayDetect(SpecialSupportSource) === false) {
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[0].use(...SpecialSupportSource);
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[1].use(...SpecialSupportSource);
                    }
                    break;
            }
        }
        switch (Instance.__MeTools.ModeLauncherSelect(ConfigureData)) {
            case "both":
                Instance.__InstanceCollect_Root.consoleLogStream.addonLog(Instance, "网站服务器模块，http、https双服务模式启动。", "info")
                ModePreviewLoader(true);
                if (Object.prototype.toString.call(httpDoubleRouter) === "[object Object]") {
                    for (let httpImpRouter in httpDoubleRouter) {
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[0].use(httpImpRouter, httpDoubleRouter[httpImpRouter]);
                    }
                }
                if (Object.prototype.toString.call(globalRouter) === "[object Object]") {
                    for (let ImpRouter in globalRouter) {
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[0].use(ImpRouter, globalRouter[ImpRouter]);
                    }
                }
                if (Object.prototype.toString.call(httpsDoubleRouter) === "[object Object]") {
                    for (let httpsImpRouter in httpsDoubleRouter) {
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[1].use(httpsImpRouter, httpsDoubleRouter[httpsImpRouter]);
                    }
                }
                if (Object.prototype.toString.call(globalRouter) === "[object Object]") {
                    for (let ImpRouter in globalRouter) {
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[1].use(ImpRouter, globalRouter[ImpRouter]);
                    }
                }
                DoubleModeSpecialSupportPreviewLoader(SpecialSupport);
                if (!httpNoNeedStatic) {
                    Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._RootDirPoint[0] =
                        Instance.__InstanceCollect_Root.PluginPoint.webApp.static(httpPath, {index: httpDefaultPage});
                    Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[0].use(
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._RootDirPoint[0]
                    )
                }
                if (httpHistoryRouter) {
                    Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[0].use(
                        Instance.__InstanceCollect_Root.PluginPoint.HistoryRouterPlugins()
                    );
                }
                if (!httpsNoNeedStatic) {
                    Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._RootDirPoint[1] =
                        Instance.__InstanceCollect_Root.PluginPoint.webApp.static(httpsPath, {index: httpsDefaultPage});
                    Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[1].use(
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._RootDirPoint[1]
                    )
                }
                if (httpsHistoryRouter) {
                    Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[1].use(
                        Instance.__InstanceCollect_Root.PluginPoint.HistoryRouterPlugins()
                    );
                }
                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteCore[0] =
                    Instance.__InstanceCollect_Root.PluginPoint.httpMode.createServer(
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[0]);
                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteCore[0].listen(httpPort, httpHostOrAddress, () => {
                    MessageTips("http", httpPort, httpHostOrAddress);
                    http_Success = true;
                });
                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteCore[1] =
                    Instance.__InstanceCollect_Root.PluginPoint.httpsMode.createServer(SSL_authLoader(SSLPrivateKey, SSLCertificate),
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint[1]);
                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteCore[1].listen(httpsPort, httpsHostOrAddress, () => {
                    MessageTips("https", httpsPort, httpsHostOrAddress);
                    https_Success = true;
                });
                break;
            case "http":
                Instance.__InstanceCollect_Root.consoleLogStream.addonLog(Instance, "网站服务器模块、http服务模式启动。", "info")
                ModePreviewLoader();
                if (Object.prototype.toString.call(httpDoubleRouter) === "[object Object]") {
                    for (let httpImpRouter in httpDoubleRouter) {
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint.use(httpImpRouter, httpDoubleRouter[httpImpRouter]);
                    }
                }
                if (Object.prototype.toString.call(globalRouter) === "[object Object]") {
                    for (let ImpRouter in globalRouter) {
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint.use(ImpRouter, globalRouter[ImpRouter]);
                    }
                }
                SingleModeSpecialSupportPreviewLoader("http", SpecialSupport);
                if (!httpNoNeedStatic) {
                    Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._RootDirPoint =
                        Instance.__InstanceCollect_Root.PluginPoint.webApp.static(httpPath, {index: httpDefaultPage});
                    Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint.use(
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._RootDirPoint
                    )
                }
                if (httpHistoryRouter) {
                    Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint.use(
                        Instance.__InstanceCollect_Root.PluginPoint.HistoryRouterPlugins()
                    );
                }
                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteCore =
                    Instance.__InstanceCollect_Root.PluginPoint.httpMode.createServer(
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint);
                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteCore.listen(httpPort, httpHostOrAddress, () => {
                    MessageTips("http", httpPort, httpHostOrAddress);
                    http_Success = true;
                });
                break;
            case "https":
                Instance.__InstanceCollect_Root.consoleLogStream.addonLog(Instance, "网站服务器模块、https服务模式启动。", "info")
                ModePreviewLoader();
                if (Object.prototype.toString.call(httpsDoubleRouter) === "[object Object]") {
                    for (let httpsImpRouter in httpsDoubleRouter) {
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint.use(httpsImpRouter, httpsDoubleRouter[httpsImpRouter]);
                    }
                }
                if (Object.prototype.toString.call(globalRouter) === "[object Object]") {
                    for (let ImpRouter in globalRouter) {
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint.use(ImpRouter, globalRouter[ImpRouter]);
                    }
                }
                SingleModeSpecialSupportPreviewLoader("https", SpecialSupport);
                if (!httpsNoNeedStatic) {
                    Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._RootDirPoint =
                        Instance.__InstanceCollect_Root.PluginPoint.webApp.static(httpsPath, {index: httpsDefaultPage});
                    Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint.use(
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._RootDirPoint
                    )
                }
                if (httpsHistoryRouter) {
                    Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint.use(
                        Instance.__InstanceCollect_Root.PluginPoint.HistoryRouterPlugins()
                    );
                }
                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteCore =
                    Instance.__InstanceCollect_Root.PluginPoint.httpsMode.createServer(SSL_authLoader(SSLPrivateKey, SSLCertificate),
                        Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteControlPoint);
                Instance.__InstanceCollect_Root.OperateInstance.webSiteInstance._webSiteCore.listen(httpsPort, httpsHostOrAddress, () => {
                    MessageTips("https", httpsPort, httpsHostOrAddress);
                    https_Success = true;
                });
                break;
        }
        let PromiseWaitProcess = new Promise((resolve, reject) => {
            let Refresh_Count = 0;
            let Refresh_Controls = setInterval(() => {
                if (Refresh_Count >= 5) {
                    reject("启动超时！");
                    clearInterval(Refresh_Controls);
                }
                switch (Instance.__MeTools.ModeLauncherSelect(ConfigureData)) {
                    case "both":
                        if (http_Success !== undefined && https_Success !== undefined) {
                            resolve("启动成功！");
                            clearInterval(Refresh_Controls);
                        }
                        break;
                    case "http":
                        if (http_Success !== undefined) {
                            resolve("启动成功！");
                            clearInterval(Refresh_Controls);
                        }
                        break;
                    case "https":
                        if (https_Success !== undefined) {
                            resolve("启动成功！");
                            clearInterval(Refresh_Controls);
                        }
                        break;
                }
            }, 1000);
        });
        let OperateStatus = false;
        let OperateInfo;
        await PromiseWaitProcess.then((val) => {
            OperateStatus = true;
            OperateInfo = val;
        }).catch((val) => {
            OperateStatus = false;
            OperateInfo = val;
        });
        if (OperateStatus) {
            return OperateInfo;
        } else {
            throw new Error(OperateInfo);
        }
    },
};